/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.api;

import cn.easyplatform.dos.EnvDo;
import cn.easyplatform.dos.UserDo;
import cn.easyplatform.engine.cmd.task.BeginCmd;
import cn.easyplatform.entities.BaseEntity;
import cn.easyplatform.entities.beans.project.DeviceMapBean;
import cn.easyplatform.entities.beans.task.TaskBean;
import cn.easyplatform.i18n.I18N;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.request.BeginRequestMessage;
import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.messages.vos.EnvVo;
import cn.easyplatform.messages.vos.GuestTaskVo;
import cn.easyplatform.services.IProjectService;
import cn.easyplatform.type.*;
import cn.easyplatform.util.MessageUtils;
import cn.easyplatform.util.RuntimeUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.*;

import java.util.HashMap;

/**
 * @Author: <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @Description:
 * @Since: 2.0.0 <br/>
 * @Date: Created in 2019/10/29 11:02
 * @Modified By:
 */
public class AnonymousCmd extends AbstractCommand<SimpleRequestMessage> {

    private final static Logger log = LoggerFactory.getLogger(AnonymousCmd.class);

    public AnonymousCmd(SimpleRequestMessage req) {
        super(req);
    }

    @Override
    public IResponseMessage<?> execute(CommandContext cc) {
        GuestTaskVo av = (GuestTaskVo) req.getBody();
        if (log.isInfoEnabled())
            log.info("api call:{} {} {}", av.getServiceId(), av.getId(), av.getVariables());
        boolean setEnv = cc.getEnv() == null || !cc.getEnv().getId().equals(av.getServiceId());
        DeviceMapBean dm = null;
        if (setEnv) {
            IProjectService projectservice = null;
            for (IProjectService ps : cc.getEngineConfiguration()
                    .getProjectServices()) {
                if (ps.getId().equals(av.getServiceId())) {
                    projectservice = ps;
                    break;
                }
            }
            if (projectservice == null)
                return MessageUtils.projectNotFound();
            dm = projectservice.getDeviceMap(null, av.getDeviceType());
            if (dm == null)
                return MessageUtils.projectDeviceInvalid();
            EnvDo env = new EnvDo(projectservice.getId(), DeviceType.getType(av.getDeviceType()),
                    projectservice.getLanguages().get(0), null, null);
            cc.setupEnv(env);
        }
        BaseEntity e = cc.getEntity(av.getId());
        if (!(e instanceof TaskBean))
            return MessageUtils.entityNotFound(EntityType.TASK.getName(),
                    av.getId());
        TaskBean ab = (TaskBean) e;
        if (Strings.isBlank(ab.getRefId()))
            return MessageUtils.entityNotFound(EntityType.TASK.getName(),
                    av.getId());
        if (ab.getAccessType() == null || ab.getAccessType() == 0 || (ab.getAccessType() == 1 && !SecurityUtils.getSubject().isAuthenticated()))
            return new SimpleResponseMessage("e200", I18N.getLabel("api.access.error"));
        if (cc.getUser() == null) {
            //设置匿名用户
            UserDo guest = RuntimeUtils.createGustUser("anonymous", UserType.TYPE_ANONYMOUS, cc.getEnv(), cc.getProjectService());
            guest.setIp(av.getIp());
            guest.setType(UserType.TYPE_ANONYMOUS);
            cc.setUser(guest);
        }
        BeginCmd cmd = new BeginCmd(new BeginRequestMessage(av));
        IResponseMessage<?> resp = cmd.execute(cc);
        if (!resp.isSuccess())
            return resp;
        if (setEnv) {
            Map<String, Object> data = new HashMap<>();
            data.put("result", resp.getBody());
            EnvVo ev = new EnvVo();
            ev.setProjectId(cc.getProjectService().getId());
            ev.setSessionId(SecurityUtils.getSubject().getSession().getId());
            ev.setDeviceType(av.getDeviceType());
            ev.setAppContext(cc.getProjectService().getEntity().getAppContext());
            ev.setTitle(cc.getProjectService().getDescription());
            ev.setLoginPage(dm.getLoginPage());
            ev.setLanguages(cc.getProjectService().getLanguages());
            if (Strings.isBlank(dm.getTheme()))
                ev.setTheme(cc.getProjectService().getEntity().getTheme());
            else
                ev.setTheme(dm.getTheme());
            data.put("env", ev);
            return new SimpleResponseMessage(data);
        } else
            return resp;
    }

    @Override
    public String getName() {
        return "apis.call";
    }
}
